<template>
  <div class="dialog-upload-avatar">
    <div>
      <div class="cropper-container">
        <!-- 裁剪组件：固定 1:1 比例（头像常用） -->
        <vue-cropper
          ref="cropper"
          :img="cropperImg"
          :info="true"
          :outputSize="0.8"
          :outputType="'jpeg'"
          :canScale="true"
          :autoCrop="true"
          :autoCropWidth="200"
          :autoCropHeight="200"
          :fixed="true"
          :freedom="true"
          :fixedNumber="[1, 1]"
          :canMove="true"
          :canMoveBox="true"
          @realTime="onRealTimeChange"
        ></vue-cropper>
        <!-- <vue-cropper
          ref="cropper"
          :img="cropperImg"   要裁剪的图片 URL 
          :info="true"
          :outputSize="0.8"  输出图片质量 
          :outputType="'jpeg'"
          :canScale="true"   允许缩放 
          :autoCrop="true"   自动裁剪
          :autoCropWidth="200"  裁剪框宽度 
          :autoCropHeight="200"  裁剪框高度 
          :freedom="true" 可以旋转
          :fixed="true"      固定比例 
          :fixedNumber="[1, 1]" 1:1 比例 
          :canMove="true"     允许拖动图片
          :canMoveBox="true" 允许拖动裁剪框
        ></vue-cropper> -->
      </div>
      <div class="action-btns">
        <el-upload
          action=""
          :auto-upload="false"
          :on-change="handleFileChange"
          accept="image/*"
          :show-file-list="false"
        >
          <el-button size="small" class="updateBtn">修改图片</el-button>
        </el-upload>
        <div>
          <el-button
            icon="el-icon-refresh-left"
            size="small"
            @click="rotateLeft"
          ></el-button>
          <el-button
            icon="el-icon-refresh-right"
            size="small"
            @click="rotateRight"
          ></el-button>
          <el-button
            icon="el-icon-refresh"
            size="small"
            @click="resetImage"
          ></el-button>
        </div>
      </div>
    </div>
    <!-- 预览裁剪后的头像 -->
    <div>
      <el-card class="avatar-preview">
        <div>
          <img
            :src="avatarUrl"
            alt="头像预览"
            style="width: 200px; height: 200px; border-radius: 50%"
          />
        </div>
      </el-card>
      <div class="preview-text">头像预览</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cropperVisible: false, // 裁剪弹窗显示状态
      cropperImg: this.avatar, // 裁剪组件的图片 URL
      avatarUrl: this.avatar, // 裁剪后的头像 URL
      changeTimer: null, // 用于防抖的定时器
      originalAvatar: this.avatar, // 添加这一行来保存原始头像
    };
  },
  props: {
    avatar: {
      type: String,
      default:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
    },
    confirmBtn: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    confirmBtn(val) {
      if (val) {
        this.$emit("updateAvatar", this.avatarUrl);
      }
    },
    avatar: {
      handler(newVal) {
        // 当avatar prop改变时，更新originalAvatar和当前显示的图片
        this.originalAvatar = newVal;
        this.cropperImg = newVal;
        this.avatarUrl = newVal;
      },
      immediate: true,
    },
  },
  methods: {
    // 选择图片后触发：将文件转为 URL 传给裁剪组件
    handleFileChange(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.cropperImg = e.target.result; // 图片 base64 地址
        this.cropperVisible = true; // 显示裁剪弹窗
      };
      reader.readAsDataURL(file.raw);
    },

    // 确认裁剪：获取裁剪后的图片并上传
    confirmCrop() {
      // 获取裁剪后的图片（base64 格式）
      this.$refs.cropper.getCropData((data) => {
        this.avatarUrl = data; // 预览裁剪结果
        // 调用接口上传（这里用 setTimeout 模拟）
        setTimeout(() => {
          this.$message.success("头像上传成功");
          this.cropperVisible = false;
        }, 500);
      });

      // 如需 blob 格式（适合大文件），用 getCropBlob：
      // this.$refs.cropper.getCropBlob((blob) => {
      //   const formData = new FormData()
      //   formData.append('avatar', blob)
      //   // 调用上传接口：axios.post('/upload', formData)
      // })
    },
    // 实时监听图片变化
    onRealTimeChange() {
      // 使用防抖机制避免频繁调用getCropData影响性能
      if (this.changeTimer) {
        clearTimeout(this.changeTimer);
      }

      this.changeTimer = setTimeout(() => {
        // 获取当前裁剪结果并更新预览
        this.$refs.cropper.getCropData((data) => {
          this.avatarUrl = data;
        });
      }, 150); // 150ms防抖延迟
    },
    // 左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    resetImage() {
      if (this.$refs.cropper.refresh) {
        this.$refs.cropper.refresh();
      } else {
        // 备用方案
        this.$refs.cropper.clearCrop();
        this.cropperImg = this.originalImage;
      }
    },
    resetCropperState() {
      if (this.changeTimer) {
        clearTimeout(this.changeTimer);
        this.changeTimer = null;
      }

      // 重置图片到原始头像
      this.cropperImg = this.originalAvatar;
      this.avatarUrl = this.originalAvatar;

      // 重置裁剪器
      if (this.$refs.cropper) {
        this.$refs.cropper.refresh();
      }
    },
  },
};
</script>

<style scoped lang="scss">
.dialog-upload-avatar {
  display: flex;
}
.cropper-container {
  width: 500px;
  height: 400px;
  margin-left: 20px;
}
.action-btns {
  margin: 15px 0 20px 20px;
  margin-top: 20px;
  width: 500px;
  display: flex;
  justify-content: space-between;
  .el-button {
    /* 基础按钮样式 */
    border: none;
    border-radius: 50px; /* 圆角效果 */
    cursor: pointer;
    font-size: 14px;
    font-weight: 600;
    color: white;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    transition: all 0.3s ease;
    /* 蓝色渐变背景 */
    background: linear-gradient(135deg, #0077cc 0%, #0099ff 100%);
    /* 阴影效果 */
    box-shadow: 0 4px 6px rgba(0, 123, 255, 0.3),
      0 1px 3px rgba(0, 123, 255, 0.1);

    /* 按钮内部发光效果 */
    position: relative;
    overflow: hidden;
  }
  .el-button::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 40%;
    background: linear-gradient(
      to bottom,
      rgba(255, 255, 255, 0.3),
      rgba(255, 255, 255, 0)
    );
    z-index: 1;
    border-radius: 50px 50px 0 0;
  }
  /* 悬停效果 */
  .el-button:hover {
    /* 渐变颜色略微变化 */
    background: linear-gradient(135deg, #0066bb 0%, #0088ee 100%);

    /* 阴影加深 */
    box-shadow: 0 6px 8px rgba(0, 102, 187, 0.4),
      0 2px 4px rgba(0, 102, 187, 0.2);

    /* 轻微放大 */
    transform: scale(1.03);
  }
}
.avatar-preview {
  margin-left: 40px;
  height: 250px;
}
.preview-text {
  margin-left: 40px;
  margin-top: 20px;
  font-weight: bold;
}
</style>
